import orderService from "../../../service/order";
import {showToast, showToastSuccess} from "../../../utils/tool";
import {simplePost} from "../../../utils/request";
import {emit} from "../../../utils/event";

const app = getApp()
const global = app.globalData

Page({
    data: {
        nav:{
            title:"商品评价",
        },
        imageUrl:global.imageUrl,
        order:null,
        info:[],
    },
    onLoad: function (options=null) {
        this.init(options)
    },
    goodsStarChange(e){
        this.setValue(e, 'goods_star')
    },
    imagesChange(e){
        this.setValue(e, 'imageArr')
    },
    contentChange(e){
        this.setValue(e, 'content')
    },
    setValue(e, key){
        const {value} = e.detail
        const {index} = e.currentTarget.dataset
        const {order, info} = this.data
        const orderItem = order.items[index]
        if (!info[index]){
            info[index] = {
                order_id:order.id,
                goods_id:orderItem.goods_id,
                order_type: order.order_type,
            }
        }
        info[index][key] = value
        this.setData({
            info,
        })
    },
    submit(){
        const {info} = this.data
        if (info.length == 0){
            return;
        }
        if (info.some(item => !item.goods_star)){
            showToast("请您为所有商品评分")
            return;
        }

        simplePost("/goodsReply/addByOrder", info).then(r => {
            showToastSuccess("评价成功", {
                timeout:() => {
                    wx.navigateBack({
                        success:() => {
                            // 评论成功的事件
                            emit(this, 'addReplyEvent',{})
                        }
                    })
                }
            })
        })


    },
    async init(options){
        // 订单信息
        const order = await orderService.find(options.order_id)
        this.setData({
            options,
            order,
        })
    }
});
